import 'dart:async';

import 'package:blue_demo/blueMaestroService.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'assetsUtil.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String title = "蓝牙未连接";

  // 写入进度
  double percent = 0;

  // 扫描的设备列表
  List<ScanResult> scanList = [];

  // 发现的服务
  List<BluetoothService> discoverServices = [];

  // 当前显示特性的服务名
  String characterServiceName = "";

  // 服务的特性
  List<BluetoothCharacteristic> characteristics = [];

  StreamSubscription<ScanResult> _blueScan;

  BlueMaestroService blueMaestroService = new BlueMaestroService();

  setPageState(String str) {
    Fluttertoast.showToast(
      msg: str,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.TOP,
    );
  }

  clearBlueData() {
    setState(() {
      title = "蓝牙未连接";
      discoverServices = [];
      characterServiceName = "";
      characteristics = [];
      scanList = [];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "蓝牙Demo",
          textAlign: TextAlign.center,
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Text(title),
            Row(
              children: [
                CupertinoButton(
                    child: Text("扫描"),
                    onPressed: () {
                      setPageState("正在扫描");
                      blueMaestroService.scanDevices((list) {
                        this.setState(() {
                          scanList = list;
                        });
                      });
                    }),
                CupertinoButton(
                    child: Text("clear"),
                    onPressed: () {
                      this.setState(() {
                        scanList = [];
                      });
                    }),
              ],
            ),
            Container(
                constraints: BoxConstraints(maxHeight: 200),
                color: Color(0x66666620),
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: scanList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        height: 45,
                        padding: EdgeInsets.only(left: 10, right: 50),
                        child: Row(
                          children: [
                            Text(
                                "${scanList[index]?.device?.name} - ${scanList[index]?.device?.id}"),
                            GestureDetector(
                              onTap: () {
                                var titleStr = blueMaestroService
                                    .connectDevice(scanList[index]?.device);
                                this.setState(() {
                                  title = titleStr;
                                  scanList = [];
                                });
                              },
                              child: Text("    连接",
                                  style: TextStyle(color: Colors.blue)),
                            )
                          ],
                        ),
                      );
                    })),
            Row(
              children: [
                CupertinoButton(
                    child: Text("发现服务"),
                    onPressed: () async {
                      setState(() {
                        discoverServices = [];
                        characterServiceName = "";
                        characteristics = [];
                      });
                      var services = await blueMaestroService.discoverService();
                      setState(() {
                        discoverServices = services;
                      });
                    }),
                CupertinoButton(
                    child: Text("设置mtu"),
                    onPressed: () async {
                      await blueMaestroService.setMtu();
                    }),
                CupertinoButton(
                    child: Text("发03"),
                    onPressed: () async {
                      await blueMaestroService.send03();
                    }),
              ],
            ),
            Container(
                constraints: BoxConstraints(maxHeight: 300),
                color: Color(0x66666620),
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: discoverServices.length,
                    itemBuilder: (BuildContext context, int index) {
                      var service = discoverServices[index];
                      return Container(
                        height: 40,
                        padding: EdgeInsets.only(left: 30),
                        child: Row(
                          children: [
                            Text("${service?.uuid}"),
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  characterServiceName =
                                      service.uuid.toString();
                                  characteristics = service.characteristics;
                                });
                              },
                              child: Text(
                                "   查看",
                                style: TextStyle(color: Colors.blue),
                              ),
                            )
                          ],
                        ),
                      );
                    })),
            characteristics.length > 0
                ? Column(
                    children: [
                      Text("$characterServiceName 服务的特性"),
                      Container(
                          constraints: BoxConstraints(maxHeight: 200),
                          color: Color(0x66666620),
                          child: ListView.builder(
                              shrinkWrap: true,
                              itemCount: characteristics.length,
                              itemBuilder: (BuildContext context, int index) {
                                var character = characteristics[index];
                                return Container(
                                  height: 40,
                                  padding: EdgeInsets.only(left: 30),
                                  child: Row(
                                    children: [
                                      Text("${character.uuid}"),
                                      GestureDetector(
                                        onTap: () async {
                                          List<int> value =
                                              await character.read();
                                          Fluttertoast.showToast(
                                              msg: value.toString(),
                                              toastLength: Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor: Colors.red,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        },
                                        child: Text(
                                          "   读取",
                                          style: TextStyle(color: Colors.blue),
                                        ),
                                      )
                                    ],
                                  ),
                                );
                              })),
                    ],
                  )
                : Text(""),
            Row(
              children: [
                CupertinoButton(
                    child: Text("进入ota模式"),
                    onPressed: () async {
                      blueMaestroService.startOTA();
                    }),
                CupertinoButton(
                    child: Text("获取ota_data"),
                    onPressed: () async {
                      blueMaestroService.getOTADataCharacter();
                    }),
                CupertinoButton(
                    child: Text("退出ota模式"),
                    onPressed: () async {
                      blueMaestroService.closeOTA();
                    }),
              ],
            ),
            Row(
              children: [
                CupertinoButton(
                    child: Text("写入040数据"),
                    onPressed: () async {
                      blueMaestroService.otaWriteTest(
                          await rootBundle.load(AssetsUtil.gbl060),
                          (pro) => {
                                this.setState(() {
                                  percent = pro;
                                })
                              });
                      // blueMaestroService.send03();
                    }),
                CupertinoButton(
                    child: Text("写入050数据"),
                    onPressed: () async {
                      // this.setState(() {
                      //    percent = (335/889 * 1000).floor()/1000;
                      // });
                      blueMaestroService.otaWriteTest(
                          await rootBundle.load(AssetsUtil.gbl050),
                          (pro) => {
                                this.setState(() {
                                  percent = pro;
                                })
                              });
                    }),
              ],
            ),
            Text("写入进度 = ${(percent * 100).round().toString()}%"),
            LinearProgressIndicator(
              value: percent,
              backgroundColor: Colors.greenAccent,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
            ),
            CupertinoButton(
                child: Text("断开连接"),
                onPressed: () async {
                  clearBlueData();
                  blueMaestroService.disconnect();
                }),
          ],
        ),
      ),
    );
  }
}
